// 定义固定的输出路径
const OUTPUT_DIR = '京东读书';  // 使用相对路径，让chrome.downloads API处理完整路径
const LOG_DIR = `${OUTPUT_DIR}/logs`;

// 添加 Service Worker 激活事件监听器
self.addEventListener('activate', (event) => {
  console.log('Service Worker 已激活');
});

// 记录日志
function log(message) {
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] ${message}\n`;
  console.log(logEntry); // 添加控制台输出
  
  // 保存到日志文件
  const logFileName = `${LOG_DIR}/collect_${new Date().toISOString().split('T')[0]}.log`;
  
  chrome.downloads.download({
    url: URL.createObjectURL(new Blob([logEntry], {type: 'text/plain'})),
    filename: logFileName,
    conflictAction: 'append'
  }, (downloadId) => {
    if (chrome.runtime.lastError) {
      console.error('保存日志失败:', chrome.runtime.lastError);
    }
  });
  
  // 同时发送到popup显示
  try {
    chrome.runtime.sendMessage({
      type: 'log',
      content: message
    }).catch(err => console.error('发送日志消息失败:', err));
  } catch (error) {
    console.error('发送日志消息时出错:', error);
  }
}

// 初始化插件状态
chrome.runtime.onInstalled.addListener(() => {
  console.log('插件已安装');
  chrome.storage.local.set({
    status: '未开始',
    progress: 0,
    log: '',
    outputPath: OUTPUT_DIR
  });
  
  log('插件已安装，文件将保存在浏览器默认下载目录的"京东读书"文件夹中');
  
  chrome.storage.local.set({
    outputConfig: {
      outputDir: OUTPUT_DIR,
      logDir: LOG_DIR
    }
  });
});

// 确保输出目录存在
async function ensureOutputDirectory() {
  try {
    await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({
        type: 'log',
        content: `准备创建输出目录: ${OUTPUT_DIR}`
      });
      
      // 使用 downloads API 测试目录是否可用
      chrome.downloads.download({
        url: URL.createObjectURL(new Blob(['test'])),
        filename: `${OUTPUT_DIR}/test.txt`,
        saveAs: false
      }, (downloadId) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          chrome.downloads.cancel(downloadId, () => resolve());
        }
      });
    });
    
    return OUTPUT_DIR;
  } catch (error) {
    chrome.runtime.sendMessage({
      type: 'log',
      content: `创建输出目录失败: ${error.message}`
    });
    throw error;
  }
}

// 保存或追加内容到Markdown文件
async function saveOrAppendContent(bookId, content, isNewChapter = true) {
  console.log('[保存内容] 开始:', { bookId, contentLength: content.length, isNewChapter });
  log(`[保存内容] 开始处理，书籍ID: ${bookId}, 内容长度: ${content.length}`);

  try {
    // 确保输出目录存在
    await ensureOutputDirectory();
    
    const fileName = `京东读书_${bookId}.md`;
    const filePath = `${OUTPUT_DIR}/${fileName}`;
    log(`[保存内容] 目标文件: ${filePath}`);
    
    // 如果是新章节，添加分隔符
    const contentToWrite = isNewChapter ? `\n\n${content}` : content;
    
    // 创建Blob对象
    const blob = new Blob([contentToWrite], {type: 'text/markdown'});
    const url = URL.createObjectURL(blob);
    log(`[保存内容] 已创建Blob，准备下载`);
    
    // 使用Promise包装下载操作
    return new Promise((resolve, reject) => {
      const downloadOptions = {
        url: url,
        filename: filePath,
        conflictAction: 'append',
        saveAs: false
      };
      
      chrome.downloads.download(downloadOptions, (downloadId) => {
        if (chrome.runtime.lastError) {
          const error = chrome.runtime.lastError;
          log(`[保存内容] 下载失败: ${error.message}`);
          URL.revokeObjectURL(url);
          reject(error);
          return;
        }
        
        log(`[保存内容] 下载已启动，ID: ${downloadId}`);
        
        // 监听下载完成事件
        chrome.downloads.onChanged.addListener(function onChanged(delta) {
          if (delta.id === downloadId) {
            if (delta.state && delta.state.current === 'complete') {
              log(`[保存内容] 下载完成: ${fileName}`);
              chrome.downloads.onChanged.removeListener(onChanged);
              URL.revokeObjectURL(url);
              resolve();
            } else if (delta.error) {
              log(`[保存内容] 下载出错: ${delta.error.current}`);
              chrome.downloads.onChanged.removeListener(onChanged);
              URL.revokeObjectURL(url);
              reject(new Error(delta.error.current));
            }
          }
        });
      });
    });
  } catch (error) {
    console.error('[保存内容] 错误:', error);
    log(`[保存内容] 出错: ${error.message}`);
    throw error;
  }
}

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('[消息接收] 收到消息:', message);

  if (message.type === 'saveContent') {
    // 使用 Promise.resolve().then() 来处理异步操作
    Promise.resolve().then(async () => {
      try {
        log(`[消息处理] 收到保存内容请求: bookId=${message.bookId}`);
        await saveOrAppendContent(message.bookId, message.content, message.isNewChapter);
        log(`[消息处理] 内容已保存成功`);
        sendResponse({ success: true });
      } catch (error) {
        console.error('[消息处理] 错误:', error);
        log(`[消息处理] 出错: ${error.message}`);
        sendResponse({ success: false, error: error.message });
      }
    });
    return true; // 表明我们将异步发送响应
  } else if (message.type === 'log') {
    // 处理日志消息
    const now = new Date();
    const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
    const newLog = `[${timeStr}] ${message.content}\n`;
    
    chrome.storage.local.get('log', (data) => {
      const logLines = (data.log || '').split('\n');
      logLines.push(newLog);
      if (logLines.length > 1000) {
        logLines.shift();
      }
      const updatedLog = logLines.join('\n');
      
      chrome.storage.local.set({ log: updatedLog }, () => {
        sendResponse({ success: true });
      });
    });
    return true; // 表明我们将异步发送响应
  } else if (message.type === 'updateProgress') {
    chrome.storage.local.set({ progress: message.progress }, () => {
      sendResponse({ success: true });
    });
    return true;
  } else if (message.type === 'updateFilePath') {
    chrome.storage.local.set({ outputPath: message.path }, () => {
      sendResponse({ success: true });
    });
    return true;
  } else if (message.type === 'updateStatus') {
    chrome.storage.local.set({ status: message.status }, () => {
      sendResponse({ success: true });
    });
    return true;
  } else if (message.type === 'updateBookTitle') {
    chrome.storage.local.set({ bookTitle: message.title }, () => {
      sendResponse({ success: true });
    });
    return true;
  }
  
  // 对于不认识的消息类型，直接返回
  sendResponse({ success: false, error: '未知的消息类型' });
  return false;
});

// 更新采集状态
async function updateCollectionStatus(status) {
  try {
    await chrome.storage.local.set({
      collectionStatus: status
    });
    log(`更新采集状态: ${JSON.stringify(status)}`);
  } catch (error) {
    console.error('更新采集状态失败:', error);
    log(`更新采集状态失败: ${error.message}`);
  }
} 